package com.midea.thread;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;

public class TestForkJoinAdd {
    public static void main(String[] args) {
        ForkJoinPool pool = new ForkJoinPool();
        AddTask main = new AddTask(1,100000);
        //invoke方法是同步调用，该线程不返回，主线程就会等待。
        long result = pool.invoke(main);
        //打印当前机器的CPU数
        System.out.println(Runtime.getRuntime().availableProcessors());
        System.out.println(result);

    }
}

class AddTask extends RecursiveTask<Long> {
    int start;
    int end;
    static final int THRESHOLD = 1000;
    public AddTask(int start,int end){
        super();
        this.start = start;
        this.end = end;
    }
    @Override
    protected Long compute() {
        //如果start和end之间差距小于THRESHOLD，直接计算
        if (end - start <= THRESHOLD) {
            long result = 0;
            for (int i = start;i<= end;i++){
                result += i;
            }
            return result;
        }else {
            //否则就要把任务分割成两个子任务
            int middle = (start+end)/2;
            AddTask task1 = new AddTask(start,middle);
            AddTask task2 = new AddTask(middle+1,end);
            invokeAll(task1,task2);
            long r1 = task1.join();
            long r2 = task2.join();
            return r1+r2;
        }
    }
}
